package com.sss.myspringsecurity.config.websocketconfig.stomp;

import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;

/**
 * websocket 连接和发送消息拦截类
 * 用于作Token验证
 * @author sss
 * @date 2020-02-17 10:01
 **/
public class MyChannelInterceptor implements ChannelInterceptor {


    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {

        StompHeaderAccessor accessor =
                MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        if (StompCommand.CONNECT.equals(accessor.getCommand()) ||StompCommand.SEND.equals(accessor.getCommand())){
            String token = accessor.getFirstNativeHeader("token");
            if (token==null) {
                return null;
            }
        }
        return message;
    }


}
